#! /usr/bin/env lua
--[[

--]]

local src_path = "/src/?.lua"
local filter_file = "/config/filter.lua"
local bean_file ="/config/bean.lua"
local route_file = "/config/route.lua"
------local logger=logger;

local setmetatable=setmetatable;
local _M={_VERSION="1.0"};
local _mt={__index=_M};
setmetatable(_M,_mt);

--local luastarContext = require"luastar.core.context"

function _M.init_pkg_path()
     local pkg_path_init = luastar_cache.get("pkg_path_init")
    if pkg_path_init then
        return
    end
    package.path = package.path..";"..ngx.var.APP_PATH..src_path
    luastar_cache.set("pkg_path_init", true)
end

function _M.getBeanFactory()
   -- return luastarContext.getBeanFactory();
   local beanFactory = luastar_cache.get("beanFactory")
    if beanFactory then
        return beanFactory
    end
    local BeanFactory = require("luastar.core.beanfactory")
    beanFactory = BeanFactory(ngx.var.APP_PATH .. bean_file)
    luastar_cache.set("beanFactory", beanFactory)
    return beanFactory
end
--[[
加载应用程序的配置参数文件。文件必须放在每个app的app_path路径下的config目录中。配置文件必须是json格式的。
参数名configName是文件名（不含json后缀的）

]]
function _M.loadJsonConfig(configName)
    local cached_config_name= "_json_"..configName;
    local app_config = luastar_cache.get(cached_config_name)
    if app_config then
        return app_config
    end
    local file = io.open(ngx.var.APP_PATH .. "/config/"..configName..".json","r");  
    ngx.log(ngx.INFO,logger.formatMsg("加载文件",ngx.var.APP_PATH .. "/config/"..configName..".json"));
    if(file==nil) then
        ngx.log(ngx.ERR,string.format("加载文件%s失败",ngx.var.APP_PATH .. "/config/"..configName..".json"))
        assert(file:close());
        return nil;
    end
    app_config = cjson.decode(file:read("*all"));       
    luastar_cache.set(cached_config_name, app_config);
    assert(file:close());
    return app_config
end
function _M.getRoute()
  local route = luastar_cache.get("route")
    if route then
        return route
    end
    local cls_route = require("com.ea.core.route")
    if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg("route filename ",ngx.var.APP_PATH .. route_file)) end
    route = cls_route(ngx.var.APP_PATH .. route_file)
    luastar_cache.set("route", route)
    return route
end

function _M.getFilter()
    local filter = luastar_cache.get("filter")
    if filter then
        return filter
    end
    local cls_Filter = require("com.ea.core.filter")
    if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg("filter filename ",ngx.var.APP_PATH .. filter_file)) end
    filter = cls_Filter(ngx.var.APP_PATH .. filter_file)
    luastar_cache.set("filter", filter)
    return filter
end

--setmetatable(_M,_mt);
return _M;